package com.app.oral.service.impl

import com.app.oral.dao.ExamPaperMapper
import com.app.oral.model.ExamPaper
import com.app.oral.model.PaperType
import com.app.oral.service.ExamPaperService
import com.app.oral.service.WeChatCloudFileDeleteService
import com.app.oral.model.FileDeleteSourceType
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

@Service
class ExamPaperServiceImpl(
    private val examPaperMapper: ExamPaperMapper,
    private val weChatCloudFileDeleteService: WeChatCloudFileDeleteService
) : ExamPaperService {
    
    private val logger = LoggerFactory.getLogger(ExamPaperServiceImpl::class.java)
    
    override fun getAllExamPapers(): List<ExamPaper> {
        return try {
            examPaperMapper.findAll()
        } catch (e: Exception) {
            logger.error("获取所有试卷失败", e)
            emptyList()
        }
    }
    
    override fun getExamPapersByGrade(targetGrade: Int): List<ExamPaper> {
        return try {
            examPaperMapper.findByTargetGrade(targetGrade)
        } catch (e: Exception) {
            logger.error("根据年级获取试卷失败: $targetGrade", e)
            emptyList()
        }
    }
    
    override fun getExamPaperById(id: Long): ExamPaper? {
        return try {
            examPaperMapper.findById(id)
        } catch (e: Exception) {
            logger.error("根据ID获取试卷失败: $id", e)
            null
        }
    }
    
    override fun createExamPaper(examPaper: ExamPaper): Boolean {
        return try {
            val result = examPaperMapper.insert(examPaper)
            logger.info("创建试卷成功: ${examPaper.title}")
            result > 0
        } catch (e: Exception) {
            logger.error("创建试卷失败: ${examPaper.title}", e)
            false
        }
    }
    
    override fun updateExamPaper(examPaper: ExamPaper): Boolean {
        return try {
            // 先获取旧试卷数据以对比文件变化
            val oldExamPaper = examPaper.id?.let { examPaperMapper.findById(it) }
            if (oldExamPaper != null) {
                // 提取旧试卷的所有文件ID
                val oldFileIds = oldExamPaper.extractAllFileIds().toSet()
                // 提取新试卷的所有文件ID
                val newFileIds = examPaper.extractAllFileIds().toSet()

                // 找出被删除的文件ID（在旧试卷中存在但在新试卷中不存在）
                val filesToDelete = oldFileIds - newFileIds

                // 删除被替换的旧文件
                if (filesToDelete.isNotEmpty()) {
                    logger.info("删除被替换的试卷文件: paperId={}, oldFiles={}", examPaper.id, filesToDelete)
                    val deleteResult = weChatCloudFileDeleteService.deleteFiles(
                        filesToDelete.toList(),
                        FileDeleteSourceType.EXAM_PAPER,
                        examPaper.id?.toString()
                    )
                    if (!deleteResult.success) {
                        logger.warn("删除旧文件失败: {}", deleteResult.message)
                    }
                }
            }

            val result = examPaperMapper.update(examPaper)
            logger.info("更新试卷成功: ${examPaper.title}")
            result > 0
        } catch (e: Exception) {
            logger.error("更新试卷失败: ${examPaper.title}", e)
            false
        }
    }
    
    override fun deleteExamPaper(id: Long): Boolean {
        return try {
            // 先获取试卷信息以提取音频文件ID
            val examPaper = examPaperMapper.findById(id)
            if (examPaper != null) {
                // 提取所有音频文件ID并删除COS文件
                val audioFileIds = weChatCloudFileDeleteService.extractAudioFileIds(examPaper)
                if (audioFileIds.isNotEmpty()) {
                    logger.info("删除试卷关联的COS音频文件: paperId={}, fileIds={}", id, audioFileIds)
                    val deleteResult = weChatCloudFileDeleteService.deleteFiles(audioFileIds, FileDeleteSourceType.EXAM_PAPER, id.toString())
                    if (!deleteResult.success) {
                        logger.warn("删除试卷COS音频文件失败: {}", deleteResult.message)
                    }
                }
            }
            
            val result = examPaperMapper.deleteById(id)
            logger.info("删除试卷成功: $id")
            result > 0
        } catch (e: Exception) {
            logger.error("删除试卷失败: $id", e)
            false
        }
    }
    
    override fun getExamPaperCount(targetGrade: Int): Int {
        return try {
            examPaperMapper.countByTargetGrade(targetGrade)
        } catch (e: Exception) {
            logger.error("获取试卷数量失败: $targetGrade", e)
            0
        }
    }
    
    override fun getExamPapersByType(paperType: PaperType): List<ExamPaper> {
        return try {
            examPaperMapper.findByPaperType(paperType)
        } catch (e: Exception) {
            logger.error("根据类型获取试卷失败: $paperType", e)
            emptyList()
        }
    }
}